var ctx=window.daijia.ctx;

var offset=0;
var limit=20;
var pagingLimit=20;//显示分页时的条数
var currentTotalElements=0;//当前显示总条数


var pageLoading=true;//是否能滚动加载
var hasShowPages=false;//是否已显示分页
var firstLoadPages=true;//分页初始化时 不自动加载

$(function(){
	
	$('#copy_activityAddress').zclip({
		path:ctx+"/assets/js/ZeroClipboard.swf",
		copy:function(){
			var value = $('#copy_activityAddress').val($('#copy_activityAddress').attr("href"));
			return value;
		},
		afterCopy:function(){
		 	$.scojs_message("复制成功", $.scojs_message.TYPE_OK);
		}
	});
	
	
});




$(document).ready(function(){
	
	
	initdata(false);
	
	$("#searchButton").click(function(){
		search_couponCode=$("#couponCode").val();
		search_phone=$("#phone").val();
		
		offset=0;
		initdata(false);
	});	
	
	$(document).on("keydown","body",function(){
		if(window.event.keyCode == 13){
			$("#searchButton").click();
		}
	});
	
	$("#clear_time").click(function(){
		$("#couponCode").val("");
		$("#phone").val("");
		search_couponCode="";
		search_phone="";
		offset=0;
		initdata(false);
	});
	
	//停止活动
	$(document).on("click",".stopthis",function(){
		var activityId=$(this).attr("data-value");
		if(window.confirm('确认要停止该活动吗？')){
			$.post(ctx+'/activity/stop',{'activityId':activityId},function(data){
				if(data.success){
					$.scojs_message("活动已停止", $.scojs_message.TYPE_OK);
					initdata(false);
				}
				else{
					$.scojs_message(data.message, $.scojs_message.TYPE_ERROR);
				}
			});
		}
	});
	
	//删除活动
	$(document).on("click",".deletethis",function(){
		var activityId=$(this).attr("data-value");
		if(window.confirm('确认要删除该活动吗？')){
			$.post(ctx+'/activity/delete',{'activityId':activityId},function(data){
				if(data.success){
					$.scojs_message("活动已删除", $.scojs_message.TYPE_OK);
					initdata(false);
				}
				else{
					$.scojs_message(data.message, $.scojs_message.TYPE_ERROR);
				}
			});
		}
	});
	
	//滚动
	$(window).scroll(function () {
        //$(window).scrollTop()这个方法是当前滚动条滚动的距离
        //$(window).height()获取当前窗体的高度
        //$(document).height()获取当前文档的高度
        var bot = 0; //bot是底部距离的高度
        if ((bot + $(window).scrollTop()) >= ($(document).height() - $(window).height())) {
           //当底部基本距离+滚动的高度〉=文档的高度-窗体的高度时；
        	if(pageLoading){
        		pageLoading=false;
        		offset+=limit;
        		initdata(true);
        	}
        }
    });
	
});
 

function initdata(isappend){
	
	$.ajax({
        url : ctx+'/activity/listData',
        type:'GET',
        async:false,
        dataType : 'json',
        data : {
        	"event":$("#event").val(),
        	"type":$("#type").val(),
        	"pager.offset":offset,
        	"limit":limit,
        },
        success : function(result){
        	var newcontent = '';
        	var totalElements=result.totalElements;
			
        	if(totalElements>0){
        		
    			
        		$(result.content).each(function(index,data){
        			var statusColor="";
        			var mainButton="";
        			var selectButton="";
        			statusColor="btn-primary";
        			
    				mainButton="<a href='"+ctx+"/activity/edit/"+data.id+"' class='btn btn-primary btn-xs'>编辑</a>";
        			
        			if(!data.stoped){
        				selectButton+="<li><a href='javascript:;' data-value='"+data.id+"' class='btn-link stopthis'>停止</a></li>";
        			}
        			selectButton+="<li><a href='javascript:;' data-value='"+data.id+"' class='btn-link deletethis'>删除</a></li>";
        			selectButton+="<li><a href='"+ctx+"/activity/detail/"+data.id+"' class='btn-link'>活动详情</a></li>";
        			if(data.activityEvent=="phoneGift"){
        				selectButton+="<li><a class='btn-link' href='"+ctx+"/activityweb/phonegift/"+data.id+"' type='button' target='_blank' id='copy_activityAddress'>进入活动地址</a></li>";
        			}
        			var allButton="<div class='btn-group'>"+
									mainButton+
								  "<button type='button' class='btn "+statusColor+" btn-xs dropdown-toggle' data-toggle='dropdown' aria-expanded='false'>"+
								    "<span class='caret'></span>"+
								    "<span class='sr-only'>Toggle Dropdown</span>"+
								  "</button>"+
								  "<ul class='dropdown-menu' role='menu'>"+
								  	selectButton+
								  "</ul>"+
								"</div>";
        			
        			var timeStatus="";
        			if(data.stoped){
        				timeStatus="<span class='label label-default status-td'>已停止</span>";
        			}
        			else{
        				if(data.timeStatus==0){
        					timeStatus="<span class='label label-warning status-td'>未开始</span>";
        				}
        				else if(data.timeStatus==1){
        					timeStatus="<span class='label label-danger status-td'>进行中</span>";
        				}
        				else if(data.timeStatus==2){
        					timeStatus="<span class='label label-default status-td'>已过期</span>";
        				}
        			}
						
        			var activityTarget="";
        			if(null!=data.activityTarget){
        				if(data.activityTarget=="passenger"){
        					activityTarget="个人客户";
        				}else if(data.activityTarget=="enterprise"){
        					activityTarget="企业客户";
        				}else if(data.activityTarget=="all"){
        					activityTarget="所有客户";
        				}
        			}
    				
    				
    				var activityType="";
    				if(data.activityType=="cash"){
    					activityType="返现（"+data.money+"元）";
    				}else if(data.activityType=="coupon"){
    					activityType="返券";
    				}else if(data.activityType=="free"){
    					activityType="首单免费";
    				}
    				
    				var orderType;
    				if(data.orderType=="daijia"){
    					orderType="<td>代驾</td>";
    				}else if(data.orderType=="zhuanche"){
    					orderType="<td>专车</td>";
    				}else{
    					orderType = "<td>-</td>";
    				}
    				
    				var completeTimes;
    				if(null!=data.completeTimes){
    					completeTimes = "<td>"+data.completeTimes+"</td>";
    				}else{
    					completeTimes = "<td>-</td>";
    				}
    				
    				var restriction;
    				if(null!=data.restriction){
    					restriction = "<td>"+data.restriction+"</td>";
    				}else if(data.restriction==0){
    					restriction = "<td>不限</td>";
    				}
    				else{
    					restriction = "<td>-</td>";
    				}
    				
    				var end="不限";
    				if(null!=data.end){
    					end=(new Date(data.end).Format("yyyy-MM-dd"));
    				}
        			
    				var mainTd="";
    				var companyNames=data.companyNames;
    				var companyNamesArr=companyNames.split(",");
    				if(main){
    					if(companyNamesArr.length==1){
    						mainTd="<td>"+companyNames+"</td>";
    					}
    					else{
    						mainTd="<td>"+companyNamesArr[0]+" 等"+companyNamesArr.length+"家公司</td>";
    					}
    				}
    				var reviewGrade = "";
    				if(1==data.reviewGrade){
						reviewGrade = "<td>完成打星</td>";
					} else if(2==data.reviewGrade){
    					reviewGrade = "<td>完成选项</td>";
					} else {
						reviewGrade = "<td>完成输入</td>";
					}

    				let activityRange = "";
    				if(data.activityRange === "zhuanxian")
						activityRange = "<td>城际</td>";
					if(data.activityRange === "zhuanche")
						activityRange = "<td>快车</td>";
    				
    				if(data.activityEvent=="newRegister"){
    					newcontent+="<tr class='grid-data tr-hui' style='display:none;'>"+
							"<td>"+timeStatus+"</td>"+
							"<td>"+data.lineName+"</td>"+
							"<td>"+activityTarget+"</td>"+
							"<td>"+activityType+"</td>"+
							mainTd+
							"<td>"+(new Date(data.start).Format("yyyy-MM-dd"))+"</td>"+
							"<td>"+end+"</td>"+
							"<td>"+allButton+"</td>"+
						"</tr>";
    				}
    				else if(data.activityEvent=="phoneGift"){
    					newcontent+="<tr class='grid-data tr-hui' style='display:none;'>"+
    									"<td>"+timeStatus+"</td>"+
				    					"<td>"+activityTarget+"</td>"+
				    					"<td>"+activityType+"</td>"+
						    					restriction+
						    					mainTd+
		    							"<td>"+(new Date(data.start).Format("yyyy-MM-dd"))+"</td>"+
		    							"<td>"+end+"</td>"+	
				    					"<td>"+allButton+"</td>"+
				    				"</tr>";
    				}
    				else if(data.activityEvent=="shareSuccess"){
	    				newcontent+="<tr class='grid-data tr-hui' style='display:none;'>"+
							"<td>"+timeStatus+"</td>"+
							"<td>"+activityType+"</td>"+
							mainTd+
							"<td>"+(new Date(data.start).Format("yyyy-MM-dd"))+"</td>"+
							"<td>"+end+"</td>"+
							"<td>"+allButton+"</td>"+
						"</tr>";
    				}
    				else if(data.activityEvent=="invite"){
	    				newcontent+="<tr class='grid-data tr-hui' style='display:none;'>"+
							"<td>"+timeStatus+"</td>"+
							"<td>"+activityType+"</td>"+
							mainTd+
							"<td>"+(new Date(data.start).Format("yyyy-MM-dd"))+"</td>"+
							"<td>"+end+"</td>"+
							"<td>"+allButton+"</td>"+
						"</tr>";
    				}
    				else if(data.activityEvent=="orderCompleteTimes"){
	    				newcontent+="<tr class='grid-data tr-hui' style='display:none;'>"+
							"<td>"+timeStatus+"</td>"+
							"<td>"+activityType+"</td>"+
							mainTd+
							"<td>"+(new Date(data.start).Format("yyyy-MM-dd"))+"</td>"+
							"<td>"+end+"</td>"+
							"<td>"+allButton+"</td>"+
						"</tr>";
    				}
    				else if(data.activityEvent=="firstOrderFree"){
	    				newcontent+="<tr class='grid-data tr-hui' style='display:none;'>"+
							"<td>"+timeStatus+"</td>"+
							mainTd+
							"<td>"+(new Date(data.start).Format("yyyy-MM-dd"))+"</td>"+
							"<td>"+end+"</td>"+
							"<td>"+allButton+"</td>"+
						"</tr>";
    				}
    				else if(data.activityEvent=="recharging"){
    					newcontent+="<tr class='grid-data tr-hui' style='display:none;'>"+
						"<td>"+timeStatus+"</td>"+
						"<td>"+activityType+"</td>"+
						mainTd+
						"<td>"+(new Date(data.start).Format("yyyy-MM-dd"))+"</td>"+
						"<td>"+end+"</td>"+
						"<td>"+allButton+"</td>"+
					"</tr>";
    				}
    				else if(data.activityEvent == "lineCoupon"){
						newcontent+=
							"<tr class='grid-data tr-hui' style='display:none;'>"+
							"<td>"+timeStatus+"</td>"+
							"<td>"+data.lineName+"</td>"+
							"<td>"+activityTarget+"</td>"+
							"<td>"+activityType+"</td>"+
							mainTd+
							"<td>"+(new Date(data.start).Format("yyyy-MM-dd"))+"</td>"+
							"<td>"+end+"</td>"+
							"<td>"+allButton+"</td>"+
							"</tr>";
					} else if(data.activityEvent == "zhuancheCoupon"){
						newcontent +=
							"<tr class='grid-data tr-hui' style='display:none;'>"+
							"<td>"+timeStatus+"</td>"+
							"<td>"+activityTarget+"</td>"+
							"<td>"+activityType+"</td>"+
							mainTd+
							"<td>"+(new Date(data.start).Format("yyyy-MM-dd"))+"</td>"+
							"<td>"+end+"</td>"+
							"<td>"+allButton+"</td>"+
							"</tr>";
					} else if(data.activityEvent == "reviewCoupon"){
						newcontent +=
							"<tr class='grid-data tr-hui' style='display:none;'>"+
							"<td>"+timeStatus+"</td>" +
							reviewGrade +
							"<td>"+activityTarget+"</td>"+
							"<td>"+activityType+"</td>" +
							activityRange +
							mainTd+
							"<td>"+(new Date(data.start).Format("yyyy-MM-dd"))+"</td>"+
							"<td>"+end+"</td>"+
							"<td>"+allButton+"</td>"+
							"</tr>";
					}
        		});
        		
        		
        	}
        	
//        	hideLoading();
        	
        	if(!isappend){
        		$(".table tbody .grid-data").remove();
        	}
        	$(".table tbody").append(newcontent);
        	
        	$(".table tbody .grid-data").each(function(index,element){
        		$(element).fadeIn(200+(index*35));
        	});
        	
        	
        	if(!hasShowPages){
        		if(!isappend){
            		currentTotalElements=result.content.length;
            		pageLoading=true;
            	}
        		else{
            		if(currentTotalElements<totalElements){
            			currentTotalElements+=result.content.length;
            			pageLoading=true;
            		}
            		else{
            			pageLoading=false;
            		}
            	}
        	}

        	if(hasShowPages){
    			firstLoadPages=true;
        		$(".pageshow li a").html("共"+totalElements+" 条数据");
        		$(".pagedata").paging(totalElements, {
        			format: '[< ncnnn >]',
        			perpage: pagingLimit,
        			page:(offset/limit)+1,
        			onSelect: function (page) {
        				limit=pagingLimit;
        				offset=(page-1)*limit;
        				if(!firstLoadPages){
        					initdata(false);
        				}
        				firstLoadPages=false;
        		    	return false;
        			},
        			onFormat: function (type) {
        				switch (type) {
        				case 'block': // n and c
        					if (!this.active)
        						return '';
        					else if (this.value != this.page)
        						return '<li><a href="#">' + this.value + '</a></li>';
        					return '<li class="active"><a href="#">' + this.value + '</a></li>';
        				case 'next': // >
        					return '<li><a href="#">&rsaquo;</a><li>';
        				case 'prev': // <
        						return '<li><a href="#">&lsaquo;</a><li>';
        				case 'first': // [
        						return '<li><a href="#">&laquo;</a><li>';
        				case 'last': // ]
        						return '<li><a href="#">&raquo;</a></li>';
        				}
        			}
        		});
        		
        	}
        	else{
        		//滚动达到pagingLimit条开始显示分页
        		if(currentTotalElements==pagingLimit){
            		
            		pageLoading=false;
            		hasShowPages=true;
            		
            		$(".pageshow").show();
            		$(".pagedata").show();
            		$(".pageshow li a").html("共"+totalElements+" 条数据");
            		$(".pagedata").paging(totalElements, {
            			format: '[< ncnnn >]',
            			perpage: pagingLimit,
            			onSelect: function (page) {
            				limit=pagingLimit;
            				offset=(page-1)*limit;
            				if(!firstLoadPages){
            					initdata(false);
            				}
            				firstLoadPages=false;
            		    	return false;
            			},
            			onFormat: function (type) {
            				switch (type) {
            				case 'block': // n and c
            					if (!this.active)
            						return '';
            					else if (this.value != this.page)
            						return '<li><a href="#">' + this.value + '</a></li>';
            					return '<li class="active"><a href="#">' + this.value + '</a></li>';
            				case 'next': // >
            					return '<li><a href="#">&rsaquo;</a><li>';
            				case 'prev': // <
            						return '<li><a href="#">&lsaquo;</a><li>';
            				case 'first': // [
            						return '<li><a href="#">&laquo;</a><li>';
            				case 'last': // ]
            						return '<li><a href="#">&raquo;</a></li>';
            				}
            			}
            		});
            		
            	}
        	}
        	
        }
	});
	
}

function showLoading(){
	if($('#loadblacklayer').length==0){
		var dw = $(".table").width();
		var dh = $(".table").height();
		var backlayer ="<div id='loadblacklayer'><div style='margin-top:"+(dh/2)+"px;margin-left:"+(dw/2)+"px;'><img src='"+ctx+"/assets/css/images/loading.gif' /></div></div>"
		$(".table tbody").append(backlayer);
		$('#loadblacklayer').css({"z-index":"9","background":"#000","opacity":"0.5","position":'absolute',"top":0,"width":dw,"height":dh});
	}
}

function hideLoading(){
	if($('#loadblacklayer').length>0){
		$('#loadblacklayer').remove();
	}
}
Date.prototype.Format = function(fmt) 
{ 
  var o = { 
    "M+" : this.getMonth()+1,                 //月份 
    "d+" : this.getDate(),                    //日 
    "h+" : this.getHours(),                   //小时 
    "m+" : this.getMinutes(),                 //分 
    "s+" : this.getSeconds(),                 //秒 
    "q+" : Math.floor((this.getMonth()+3)/3), //季度 
    "S"  : this.getMilliseconds()             //毫秒 
  }; 
  if(/(y+)/.test(fmt)) 
    fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); 
  for(var k in o) 
    if(new RegExp("("+ k +")").test(fmt)) 
  fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
  return fmt; 
}
